#include "ircchannel.h"

irc_channel_t *init_channel() {
	irc_channel_t *irc_channel = malloc(sizeof(irc_channel_t));
	irc_channel->prev = NULL;
	irc_channel->next = NULL;
	irc_channel->name = NULL;
	return irc_channel;
}

void free_channel(irc_channel_t *irc_channel) {
	irc_channel = find_first(irc_channel);
	while(irc_channel->next) {
		irc_channel = irc_channel->next;
		if(irc_channel->prev->name) free(irc_channel->prev->name);
		free(irc_channel->prev);
	}
	if(irc_channel->name) free(irc_channel->name);
	free(irc_channel);
}



void add_channel(irc_channel_t *irc_channel, char *channel) {
	int length;
	if(!irc_channel || !channel) return;
	irc_channel = find_last(irc_channel);
	length = strlen(channel);
	if(irc_channel->name != NULL) {
		irc_channel->next		= init_channel();
		irc_channel->next->prev = irc_channel;
		irc_channel				= irc_channel->next;
	} 
	irc_channel->name = malloc(sizeof(char) * (length + 1));
	strncpy(irc_channel->name, channel, length);
	irc_channel->name[length] = '\0';
}

BOOL contains_channel(irc_channel_t *irc_channel, char *channel) {
	if(!irc_channel || !channel) return FALSE;
	irc_channel = find_first(irc_channel);
	while(irc_channel->next) {
		if(!strcmp(irc_channel->name, channel)) 
			return TRUE;
		irc_channel = irc_channel->next;
	}
	if(!strcmp(irc_channel->name, channel)) 
		return TRUE;
	return FALSE;
}

void remove_channel(irc_channel_t *irc_channel, char *channel) {
	irc_channel = find_first(irc_channel);
	do {
		if(irc_channel->name && !strcmp(irc_channel->name, channel)) {
			if(irc_channel->prev && irc_channel->next) {
				irc_channel->prev->next = irc_channel->next;
				irc_channel->next->prev = irc_channel->prev;
			} else if (irc_channel->next) {
				irc_channel->next->prev = NULL;
			} else {
				// if it's the only node, just free name
				free(irc_channel->name);
				irc_channel->name = NULL;
				return;
			}
			free(irc_channel->name);
			free(irc_channel);
			return;
		}
		irc_channel = irc_channel->next;
	} while(irc_channel && irc_channel->next);
}

irc_channel_t *find_first(irc_channel_t *irc_channel) {
	while(irc_channel->prev)
		irc_channel = irc_channel->prev;
	return irc_channel;
}	

irc_channel_t *find_last(irc_channel_t *irc_channel) {
	while(irc_channel->next)
		irc_channel = irc_channel->next;
	return irc_channel;
}	
